package site.isscloud.jt809;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class LoginRequest {
    private String userId;          // 20字节
    private byte[] password;        // 20字节 (MD5)
    private String downLinkIp;      // 32字节
    private int downLinkPort;       // 2字节
    
    public LoginRequest(String userId, String password, String downLinkIp, int downLinkPort) {
        this.userId = userId;
        this.password = JT809Utils.md5_20(password);
        this.downLinkIp = downLinkIp;
        this.downLinkPort = downLinkPort;
    }
    
    // 从字节数组解析
    public LoginRequest(byte[] data) {
        ByteBuffer buffer = ByteBuffer.wrap(data).order(ByteOrder.BIG_ENDIAN);
        
        byte[] userIdBytes = new byte[20];
        buffer.get(userIdBytes);
        this.userId = new String(userIdBytes).trim();
        
        this.password = new byte[20];
        buffer.get(this.password);
        
        byte[] ipBytes = new byte[32];
        buffer.get(ipBytes);
        this.downLinkIp = new String(ipBytes).trim();
        
        this.downLinkPort = JT809Utils.readUnsignedShort(buffer);
    }
    
    // 转换为字节数组
    public byte[] toByteArray() {
        ByteBuffer buffer = ByteBuffer.allocate(20 + 20 + 32 + 2)
                .order(ByteOrder.BIG_ENDIAN);
        
        // 写入用户ID (固定20字节)
        byte[] userIdBytes = new byte[20];
        byte[] srcUserId = userId.getBytes();
        System.arraycopy(srcUserId, 0, userIdBytes, 0, Math.min(srcUserId.length, 20));
        buffer.put(userIdBytes);
        
        // 写入密码 (固定20字节)
        buffer.put(password, 0, Math.min(password.length, 20));
        
        // 写入下行IP (固定32字节)
        byte[] ipBytes = new byte[32];
        byte[] srcIp = downLinkIp.getBytes();
        System.arraycopy(srcIp, 0, ipBytes, 0, Math.min(srcIp.length, 32));
        buffer.put(ipBytes);
        
        // 写入端口
        buffer.putShort((short) downLinkPort);
        
        return buffer.array();
    }
    
    // Getters
    public String getUserId() { return userId; }
    public byte[] getPassword() { return password; }
    public String getDownLinkIp() { return downLinkIp; }
    public int getDownLinkPort() { return downLinkPort; }
}
